import React, { Component } from "react";
import { Text, View, StyleSheet, TouchableOpacity, Image, TextInput, Linking, Platform, Dimensions, Clipboard, ScrollView } from 'react-native';
import Constant from '../../utils/Constant'//全局变量
import { getImgUrl } from '../../utils/ComFunction';
import HttpUtils from "../../utils/HttpUtils";
import HttpUrls from "../../utils/HttpUrls";
import Header from "../../components/header";
import { ToastToUser } from "../../utils/CustomToast";
import Loading from "../../utils/Loading";
import DatePickerPart from '../../components/Tool/DatePickerPart'
import { detectionStatus } from '../../utils/Enum'
import { conditionObjWithType } from '../../utils/Conditions'
import AlertCommonView from "../../components/Tool/AlertCommonView";
import moment from 'moment';
import AsyncImage from "../../components/image/AsyncImage";
import { shareWebToSession, shareWebToTimeline } from '../../utils/WeChatUtils'

let navigation = null;
const screenW = Dimensions.get('window').width;


export default class DetectionDetailPage extends Component {

    constructor(props) {
        super(props);
        let data = this.props.route.params && this.props.route.params.data ? this.props.route.params.data : {}
        this.state = {
            data,
            showAlertCommonView: false,
        };
    }

    componentDidMount() {
        this.getdetectionOrderDetail()
    }

    getdetectionOrderDetail() {
        let param = {
            id: this.state.data.detectionOrderId,
        }
        if (this.Loading) {
            this.Loading.show();
        }
        HttpUtils.getRequest(HttpUrls.getdetectionOrderDetail, param)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                if (result.code == 0) {
                    this.setState({
                        data: result.data
                    })
                } else {
                    ToastToUser(result.msg ? result.msg : result.statusText)
                }
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });
    }

    render() {
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <Header navigation={navigation} Title={'检测单'} />
                <ScrollView style={{ flex: 1 }} showsVerticalScrollIndicator={false}>
                    <AsyncImage style={styles.carImg} source={{ uri: getImgUrl(this.state.data.mainPic) }} defaultSource={require('source/image/comm/sc_default.png')} />
                    <View style={styles.contentBox}>
                        <View style={styles.brandBox}>
                            <Text style={styles.brandText}>{this.state.data.carName}</Text>
                            <View style={[styles.detectionStatusBox, { backgroundColor: this.state.data.detectionStatus == detectionStatus.detectionStatusWaitForDetection ? '#FFF2E5' : '#F4F4F4' }]}>
                                <Text style={[styles.statusText, { color: this.state.data.detectionStatus == detectionStatus.detectionStatusWaitForDetection ? '#FF7B00' : this.state.data.detectionStatus == detectionStatus.detectionStatusDetected ? '#49CC69' : '#999999' }]}>{conditionObjWithType('detectionStatus')[this.state.data.detectionStatus]}</Text>
                            </View>
                        </View>
                        <View style={[styles.brandBox, { marginTop: 10 }]}>
                            <Text style={styles.vcodeText}>{'VIN：' + this.state.data.vcode}</Text>
                            <TouchableOpacity
                                style={styles.copyBox}
                                onPress={() => {
                                    Clipboard.setString(this.state.data.vcode);
                                    ToastToUser('复制成功')
                                }}
                            >
                                <Text style={styles.copyText}>复制</Text>
                            </TouchableOpacity>
                        </View>
                        <View style={[styles.brandBox, { marginTop: 18 }]}>
                            <Text style={styles.styleText}>{'检测类型'}</Text>
                            <Text style={styles.style1Text}>{this.state.data.detectionTypeName}</Text>
                            <Text style={[styles.styleText, { marginLeft: 83 }]}>{'检测师'}</Text>
                            <Text style={styles.style1Text}>{this.state.data.inspectorName}</Text>
                        </View>

                        <View style={[styles.brandBox, { marginTop: 16 }]}>
                            <Text style={styles.styleText}>{'下单时间'}</Text>
                            <Text style={styles.style1Text}>{moment(this.state.data.orderTime).format("YYYY-MM-DD HH:mm")}</Text>
                        </View>
                        {
                            //已完成
                            this.state.data.detectionStatus == detectionStatus.detectionStatusDetected ?
                                <View style={[styles.brandBox, { marginTop: 16 }]}>
                                    <Text style={styles.styleText}>{'生成时间'}</Text>
                                    <Text style={styles.style1Text}>{moment(this.state.data.reportTime).format("YYYY-MM-DD HH:mm")}</Text>
                                </View>
                                :
                                null

                        }

                        {
                            this.state.data.detectionResult ?
                                <View style={{ flexDirection: 'column', marginVertical: 20 }}>
                                    <Text style={styles.detectResultText}>检测结果</Text>
                                    <View style={styles.detectResultBox}>
                                        <Text style={styles.detectResultText1}>{this.state.data.detectionResult}</Text>
                                    </View>
                                </View>
                                :
                                null
                        }
                    </View>
                </ScrollView>

                {
                    this.state.data.detectionStatus == detectionStatus.detectionStatusWaitForDetection ?
                        <View style={[styles.bottomBox, { height: 60 + Constant.bottomHeight }]}>
                            <TouchableOpacity
                                style={styles.cancelBox}
                                activeOpacity={0.8}
                                onPress={() => {
                                    this.setState({
                                        showAlertCommonView: true
                                    })
                                }}
                            >
                                <Text style={{ fontSize: 16, color: '#222' }}>取消订单</Text>
                            </TouchableOpacity>
                            <TouchableOpacity
                                style={styles.sureBox}
                                activeOpacity={0.8}
                                onPress={() => {
                                    let url = 'https://cmg-report.kmruizhi.net/app/appdown.html?orderNo=' + this.state.data.orderNo + '&inspector=' + this.state.data.inspectorUserId
                                    console.log('url = ', url);
                                    Linking.openURL(url).catch(err => console.error('An error occurred', err));
                                }}
                            >
                                <Text style={{ fontSize: 16, color: '#222' }}>立即检测</Text>
                            </TouchableOpacity>
                        </View>
                        :
                        this.state.data.detectionStatus == detectionStatus.detectionStatusDetected ?
                            <View style={[styles.bottomBox, { height: 60 + Constant.bottomHeight }]}>
                                <TouchableOpacity
                                    style={styles.itemBox}
                                    activeOpacity={0.8}
                                    onPress={() => {
                                        let url = this.state.data.reportPdf
                                        console.log('url = ', url);
                                        Linking.openURL(url).catch(err => console.error('An error occurred', err));
                                    }}
                                >
                                    <Image style={styles.itemImg} source={require('source/image/download_icon.png')} />
                                    <Text style={{ fontSize: 10, color: '#333' }}>下载</Text>
                                </TouchableOpacity>
                                <TouchableOpacity
                                    style={styles.itemBox}
                                    activeOpacity={0.8}
                                    onPress={() => {
                                        let shareObj = {
                                            title: this.state.data.vcode+'的检测报告',
                                            description: this.state.data.carName,
                                            type: 'news',
                                            webpageUrl: this.state.data.reportH5,
                                            thumbImage: 'https://img.shuaiche.com/img/statics/app/contract/icon_pdf.png'
                                        }

                                        shareWebToSession(shareObj)
                    
                                    }}
                                >
                                    <Image style={styles.itemImg} source={require('source/image/share_icon.png')} />
                                    <Text style={{ fontSize: 10, color: '#333' }}>分享</Text>
                                </TouchableOpacity>
                                <TouchableOpacity
                                    style={styles.sureBox}
                                    activeOpacity={0.8}
                                    onPress={() => {
                                        let url = this.state.data.reportH5
                                        navigation.navigate('WebView', { source: url })
                                    }}
                                >
                                    <Text style={{ fontSize: 16, color: '#222' }}>查看报告</Text>
                                </TouchableOpacity>
                            </View>
                            :
                            null
                }



                <Loading onRef={(ref) => (this.Loading = ref)} />

                {
                    this.state.showAlertCommonView ?
                        <AlertCommonView
                            title={'提示'}
                            content={'是否取消该检测订单？'}
                            cancelBtnText={'否'}
                            sureBtnText={'是'}
                            cancelHandler={() => {
                                this.setState({
                                    showAlertCommonView: false
                                })
                            }}
                            sureHandler={() => {
                                this.setState({
                                    showAlertCommonView: false
                                })
                                this.cancelDetect()
                            }}
                        />
                        :
                        null
                }

            </View>
        );
    }

    cancelDetect() {
        let param = {
            detectionOrderId: this.state.data.detectionOrderId,
            operator: Constant.userInfo.fullname
        }
        if (this.Loading) {
            this.Loading.show();
        }
        HttpUtils.postRequest(HttpUrls.cancelDetectionOrder, param)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                if (result.code == 0) {
                    ToastToUser('取消成功')
                    setTimeout(() => {
                        if (this.props.route.params && this.props.route.params.completion) {
                            this.props.route.params.completion()
                        }
                    }, 500);
                } else {
                    ToastToUser(result.msg ? result.msg : result.statusText)
                }
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });
    }


};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        flexDirection: 'column',

    },
    carImg: {
        width: '100%',
        height: screenW * 0.7,
    },
    contentBox: {
        flex: 1,
        marginTop: -10,
        borderTopLeftRadius: 10,
        borderTopRightRadius: 10,
        backgroundColor: '#fff',
        flexDirection: 'column',
        paddingHorizontal: 16,
        paddingTop: 16,
    },
    brandBox: {
        flexDirection: 'row',
        alignItems: 'flex-start',
        alignItems: 'center'
    },
    brandText: {
        flex: 1,
        fontSize: 16,
        color: '#333333',
        fontWeight: 'bold',
        lineHeight: 22,
    },
    detectionStatusBox: {
        marginLeft: 10,
        paddingHorizontal: 14,
        height: 26,
        backgroundColor: '#FFF2E5',
        borderRadius: 2,
        justifyContent: 'center',
        alignItems: 'center'
    },
    statusText: {
        fontSize: 14,
        color: '#FF7B00',
        fontWeight: 'bold',
    },
    vcodeText: {
        fontSize: 12,
        color: '#666',
    },
    copyBox: {
        height: 17,
        width: 42,
        justifyContent: 'center',
        alignItems: 'center',
        marginLeft: 10,
        borderColor: '#999999',
        borderWidth: 1,
        borderRadius: 2,
    },
    copyText: {
        fontSize: 12,
        color: '#666',
    },
    styleText: {
        fontSize: 14,
        color: '#666'
    },
    style1Text: {
        fontSize: 14,
        color: '#333',
        marginLeft: 8,
    },

    detectResultText: {
        color: '#333',
        fontSize: 14,
        fontWeight: '500'
    },
    detectResultText1: {
        color: '#333',
        fontSize: 14,
        lineHeight: 16
    },
    detectResultBox: {
        marginTop: 12,
        width: '100%',
        minHeight: 88,
        borderRadius: 6,
        backgroundColor: '#F4F4F4',
        padding: 12,
    },

    bottomBox: {
        paddingHorizontal: 16,
        width: '100%',
        paddingTop: 8,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'flex-start',
        backgroundColor: '#fff',
        borderTopWidth: 0.5,
        borderTopColor: '#E5E5E5',
    },
    cancelBox: {
        marginRight: 8,
        flex: 1.2,
        height: 44,
        borderRadius: 23,
        backgroundColor: '#F5F5F5',
        justifyContent: 'center',
        alignItems: 'center'
    },
    itemBox: {
        marginRight: 10,
        width: 40,
        height: 44,
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
    },
    itemImg: {
        width: 18,
        height: 18,
        marginBottom: 5,
    },
    sureBox: {
        flex: 1.8,
        height: 44,
        borderRadius: 23,
        backgroundColor: '#FFE000',
        justifyContent: 'center',
        alignItems: 'center'
    }


});